package com.enation.app.shop.front.api.appcontroller;




import com.enation.app.base.core.model.Member;
import com.enation.app.base.core.service.IMemberManager;
import com.enation.app.base.core.service.IRegionsManager;
import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IProductManager;
import com.enation.app.shop.core.member.model.MemberAddress;
import com.enation.app.shop.core.member.service.IMemberAddressManager;
import com.enation.app.shop.core.member.service.IMemberReceiptManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.model.OrderItem;
import com.enation.app.shop.core.order.model.SellBack;
import com.enation.app.shop.core.order.model.SellBackGoodsList;
import com.enation.app.shop.core.order.model.support.CartItem;
import com.enation.app.shop.core.order.model.support.OrderPrice;
import com.enation.app.shop.core.order.plugin.cart.CartPluginBundle;
import com.enation.app.shop.core.order.service.*;
import com.enation.app.shop.core.other.service.IActivityManager;
import com.enation.app.shop.front.api.appdto.OrderDetail;
import com.enation.app.shop.front.api.random.IMobileRandomManager;
import com.enation.app.shop.front.api.sellbackgallery.Sellbackgallery;
import com.enation.eop.SystemSetting;
import com.enation.eop.sdk.context.EopSetting;
import com.enation.eop.sdk.context.UserConext;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.context.webcontext.ThreadContextHolder;
import com.enation.framework.database.IDaoSupport;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.FileUtil;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * 订单类
 */
@Controller
@RequestMapping("/app/order")
public class OrderAppController {
    @Autowired
    private IOrderFlowManager orderFlowManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private IMemberAddressManager memberAddressManager;
    @Autowired
    private IExpressManager expressManager;
    @Autowired
    private ICartManager cartManager;
    @Autowired
    private CartPluginBundle cartPluginBundle;
    @Autowired
    private IPaymentManager paymentManager;
    @Autowired
    private IRegionsManager regionsManager;
    @Autowired
    private IMemberReceiptManager memberReceiptManager;
    @Autowired
    private IDaoSupport daoSupport;
    @Autowired
    private IGoodsManager goodsManager;
    @Autowired
    private IMemberManager memberManager;
    @Autowired
    private ISellBackManager sellBackManager;
    @Autowired
    private IMobileRandomManager mobileRandomManager;
    @Autowired
    private IProductManager productManager;


    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private IActivityManager activityManager;



    /**
     * 创建订单，需要购物车中有商品
     //* @param address_id:收货地址id.int型，必填项
     //* @param payment_id:支付方式id，int型，必填项
     //* @param shipping_id:配送方式id，int型，必填项
     //* @param shipDay：配送时间，String型 ，可选项
     //* @param shipTime，String型 ，可选项
     //* @param remark，String型 ，可选项
     *
     * @return 返回json串
     * result  为1表示添加成功0表示失败 ，int型
     * message 为提示信息
     *
     */
    @ResponseBody
    @RequestMapping(value="/create", produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult create(){
        try{
            Order order  = this.createOrder();
            return JsonResultUtil.getObjectJson(order, "order");
        }catch(RuntimeException e){
            //e.printStackTrace();
            this.logger.error("创建订单出错", e);
            return JsonResultUtil.getErrorJson("创建订单出错:" + e.getMessage());
        }
    }

    /**
     *   //创建订单
     * @param orderInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("/creatOrder")
    public  JsonResult createOrde(@RequestBody OrderDetail orderInfo){
        List<CartItem> cartItems=orderInfo.getCartItems();
        int a=cartItems.size();
        Order order=new Order();
        order.setAddress_id(orderInfo.getAddress_id());
        order.setShip_name(orderInfo.getShip_name());//ship_name
        order.setShip_mobile(orderInfo.getShip_mobile());//ship_mobile
        order.setShip_addr(orderInfo.getShip_addr());//ship_addr
        order.setGoods_num(orderInfo.getGoods_num());//goods_num商品数量
        order.setShipping_id(OrderStatus.SHIP_NO);
        order.setShipping_type("牧中工作人员派送");
        order.setShipping_area("上海-卢湾区-卢湾区");
        order.setDepotid(1);
        if (orderInfo.getPayment_id()==3){
            order.setPayment_id(orderInfo.getPayment_id());//payment_id
            order.setStatus(OrderStatus.ORDER_NOT_PAY);
            order.setPayment_name("货到付款");
            order.setPayment_type("cod");//payment_type
        }else {
            order.setPayment_id(5);//payment_id
            order.setStatus(OrderStatus.ORDER_CONFIRM);
            order.setPayment_name("信用额度支付");
            order.setPayment_type("online");//payment_type
        }
        order.setRemark(orderInfo.getRemark());//remark
        if(orderInfo.getMember_id()==null){
            return JsonResultUtil.getErrorJson("您还没有用户id");
        }
        order.setMember_id(orderInfo.getMember_id());//order_id
        List<CartItem> cartItems1=new ArrayList<CartItem>();
        double goodprice=0.0;
        List<Double> doubles=new ArrayList<Double>();
        for (CartItem cartItem:cartItems){
            CartItem cartItem1=new CartItem();
            int productid=cartItem.getProduct_id();
            String producsn=productManager.get(productid).getSn();
//            cartItem1.setCatid(1);
            cartItem1.setSn(producsn);
            cartItem1.setPolicy_number(cartItem.getPolicy_number());
            cartItem1.setUnit(cartItem.getPolicy_number());
            cartItem1.setPrice(cartItem.getPrice());//price
            cartItem1.setMktprice(cartItem.getPrice());//price
            cartItem1.setGoods_id(cartItem.getGoods_id());//goods_id
            Integer goodsid=cartItem.getGoods_id();
            String thumbnail=goodsManager.get(goodsid).get("thumbnail").toString();
            String  goodname=goodsManager.get(goodsid).get("name").toString();
            cartItem1.setImage_default(thumbnail);
            cartItem1.setName(goodname);//name
            cartItem1.setNum(cartItem.getNum());//num
            cartItem1.setProduct_id(cartItem.getProduct_id());
            goodprice=cartItem.getNum()*cartItem.getPrice();
            doubles.add(goodprice);
            cartItems1.add(cartItem1);
        }
        Double goodpricetemp=0.0;
        for (Double d:doubles){
            goodpricetemp+=d;
        }
        order.setNeed_pay_money(goodpricetemp);
        order.setGainedpoint(goodpricetemp.intValue());
        order.setConsumepoint(goodpricetemp.intValue());
        order.setGoods_amount(goodpricetemp);
        order.setOrder_amount(goodpricetemp);
        order.setWeight(0.0);
        order.setDiscount(0.0);
        order.setShipping_amount(0.0);
        order.setShip_day("任意日期");
        order.setShip_time("任意时间");
        order.setGoods_num(a);
        if (orderInfo.getReceipt()==1){
            order.setReceipt(1);
            order.setReceipt_content(orderInfo.getReceipt_content());
            order.setReceipt_duty(orderInfo.getReceipt_duty());
            order.setReceipt_type(orderInfo.getReceipt_type());
            order.setReceipt_name(orderInfo.getReceipt_name());
            if (orderInfo.getReceipt_type()==1){
                order.setReceipt_title("个人");
            }else {
                order.setReceipt_title("企业");
            }
        }else {
            order.setReceipt(2);
        }
        String sessionid=createSession();
        //EAF8B5FFFF80785B21C041D854C02F4E
        Order order1=this.orderFlowManager.add(order,cartItems1,sessionid,orderInfo.getMember_id());
        if (order1==null){
            return JsonResultUtil.getErrorJson("创建订单失败");
        }else {
            String sn=order1.getSn();
            Integer id=order1.getOrder_id();
            return JsonResultUtil.getObjectMessageJson(id,"创建订单成功返回订单id");
        }
    }

    /**
     * 创建订单-需要request信息中 带以下参数
     // * @param address_id:收货地址id.int型，必填项
     //* @param payment_id:支付方式id，int型，必填项
     //* @param shipping_id:配送方式id，int型，必填项
     //* @param shipDay：配送时间，String型 ，可选项
     //* @param shipTime，String型 ，可选项
     //* @param remark，String型 ，可选项
     * @return
     */
    private Order createOrder(){
        HttpServletRequest request  = ThreadContextHolder.getHttpRequest();


        Integer shippingId = StringUtil.toInt(request.getParameter("typeId"),null);
        if(shippingId==null ){
            throw new RuntimeException("配送方式不能为空");
        }

        Integer paymentId = StringUtil.toInt(request.getParameter("paymentId"),0);
//		修改为提交订单后，选择支付方式付款，修改人：xulipeng
// 		if(paymentId==0 ){
// 			throw new RuntimeException("支付方式不能为空");
// 		}

        Order order = new Order() ;
        order.setShipping_id(shippingId); //配送方式
        order.setPayment_id(paymentId);//支付方式
        String payType="";
        if(paymentId.intValue()==0){
            order.setIs_online(1);
            payType="online";
        }else{
            payType = this.paymentManager.get(paymentId).getType();
        }

        Integer addressId = StringUtil.toInt(request.getParameter("addressId"), false);

        MemberAddress address = new MemberAddress();
        address = this.createAddress();
        if ("cod".equals(payType)) {
            // 如果用户选择的收货地区不支持货到付款(对省、市、区三级都要做判断)
            if (regionsManager.get(address.getProvince_id()).getCod() != 1) {
                throw new RuntimeException("您选择的收货地址不支持货到付款！");
            }

            if (regionsManager.get(address.getCity_id()).getCod() != 1) {
                throw new RuntimeException("您选择的收货地址不支持货到付款！");
            }

            if (regionsManager.get(address.getRegion_id()).getCod() != 1) {
                throw new RuntimeException("您选择的收货地址不支持货到付款！");
            }
        }
        order.setShip_provinceid(address.getProvince_id());
        order.setShip_cityid(address.getCity_id());
        order.setShip_regionid(address.getRegion_id());
        if(address.getTown_id()!=null&&!address.getTown_id().equals(-1)){
            order.setShip_townid(address.getTown_id());
        }
        order.setShip_addr(address.getAddr());
        order.setShip_mobile(address.getMobile());
        order.setShip_tel(address.getTel());
        order.setShip_zip(address.getZip());
        if(address.getTown_id()!=null&&!address.getTown_id().equals(-1)){
            order.setShipping_area(address.getProvince()+"-"+ address.getCity()+"-"+ address.getRegion()+"-"+address.getTown());
        }else{
            order.setShipping_area(address.getProvince()+"-"+ address.getCity()+"-"+ address.getRegion());
        }
        order.setShip_name(address.getName());
        order.setRegionid(address.getRegion_id());

        //新的逻辑：只要选中了“保存地址”，就会新增一条收货地址，即使数据完全没有修改
        if ("yes".equals(request.getParameter("saveAddress"))) {
            Member member = UserConext.getCurrentMember();
            if (member != null) {
                address.setAddr_id(null);
                addressId= this.memberAddressManager.addAddress(address);
            }
        }
        address.setAddr_id(addressId);
        order.setMemberAddress(address);
        order.setShip_day(request.getParameter("shipDay"));
        order.setShip_time(request.getParameter("shipTime"));
        order.setRemark(request.getParameter("remark"));
        order.setAddress_id(address.getAddr_id());//保存本订单的会员id

        /**发票*/

        Integer receipt = Integer.parseInt(request.getParameter("receipt").toString());
        order.setReceipt(receipt);
        /**判断是否需要发票*/
        if(receipt==1){
            String receipt_title = request.getParameter("receiptTitle");
            String receipt_content = request.getParameter("receiptContent");
            String receipt_duty = request.getParameter("receiptDuty");
            Integer receipt_type = Integer.parseInt(request.getParameter("receiptType"));
            order.setReceipt_content(receipt_content);
            order.setReceipt_title(receipt_title);
            order.setReceipt_duty(receipt_duty);
            order.setReceipt_type(receipt_type);
        }

        String sessionid =request.getSession().getId();
        List<CartItem> itemList  = this.cartManager.selectListGoods(sessionid);
        if(itemList==null||itemList.size()==0){
            throw new RuntimeException("购物车不能为空");
        }
        OrderPrice orderPrice =   this.cartManager.countPrice(itemList, shippingId,address.getRegion_id()+"");

        //激发价格计算事件
        orderPrice  = this.cartPluginBundle.coutPrice(orderPrice);
        order.setOrderprice(orderPrice);

        Integer activity_id = StringUtil.toInt(request.getParameter("activity_id"),0);

        //如果促销活动id不等于0
        if (activity_id != 0) {

            //如果当前促销活动有效
            if (this.activityManager.checkActivity(activity_id) == 0) {
                //以下为当有促销活动时，提交订单，下列信息要set进订单信息中
                //add by DMRain 2016-6-8
                String gift_id = request.getParameter("gift_id");
                String bonus_id = request.getParameter("bonus_id");
                String act_discount = request.getParameter("act_discount");
                String activity_point = request.getParameter("activity_point");
                String freeShip = request.getParameter("freeShip");

                //如果促销活动赠送的赠品id不为空
                if (gift_id != null) {
                    order.setGift_id(Integer.parseInt(gift_id));
                }

                //如果促销活动赠送的优惠券id不为空
                if (bonus_id != null) {
                    order.setBonus_id(Integer.parseInt(bonus_id));
                }

                //如果促销活动减免的现金金额不为空
                if (act_discount != null) {
                    order.setAct_discount(Double.parseDouble(act_discount));
                    order.setNeed_pay_money(order.getNeed_pay_money() - Double.parseDouble(act_discount));
                }

                //如果促销活动赠送的积分不为空
                if (activity_point != null) {
                    order.setActivity_point(Integer.parseInt(activity_point));
                }

                //如果促销活动拥有免邮费的优惠条件
                if (freeShip != null) {
                    order.setNeed_pay_money(order.getNeed_pay_money() - order.getShipping_amount());
                    order.setOrder_amount(order.getOrder_amount() - order.getShipping_amount());
                    order.setShipping_amount(0.00);
                }
            }
        }
        return	this.orderFlowManager.add(order,itemList,sessionid);
    }



    /**
     * 创建地址-需要request中 带地址参数
     //* @param shipName 收货人 【必填】
     //* @param shipTel 电话 【选填】
     //* @param shipMobile 手机 【选填】
     //* @param province_id 省份id 【必填】
     //* @param city_id 城市id 【必填】
     //* @param region_id 地区id 【必填
     //* @param province -- 【必填】
     //* @param city -- 【必填】
     //* @param region -- 【必填
     //* @param shipAddr 收获地址
     //* @param shipZip -- 【必填】
     * @return
     */
    private MemberAddress createAddress(){
        HttpServletRequest request  = ThreadContextHolder.getHttpRequest();

        MemberAddress address = new MemberAddress();


        String name = request.getParameter("shipName");
        address.setName(name);

        String tel = request.getParameter("shipTel");
        address.setTel(tel);

        String mobile = request.getParameter("shipMobile");
        address.setMobile(mobile);

        String province_id = request.getParameter("province_id");
        if(province_id!=null){
            address.setProvince_id(Integer.valueOf(province_id));
        }

        String city_id = request.getParameter("city_id");
        if(city_id!=null){
            address.setCity_id(Integer.valueOf(city_id));
        }

        String region_id = request.getParameter("region_id");
        if(region_id!=null){
            address.setRegion_id(Integer.valueOf(region_id));
        }
        String town_id = request.getParameter("town_id");
        if(town_id!=null&&!town_id.equals("")){
            address.setTown_id(Integer.valueOf(town_id));
        }

        String province = request.getParameter("province");
        address.setProvince(province);

        String city = request.getParameter("city");
        address.setCity(city);

        String region = request.getParameter("region");
        address.setRegion(region);

        String town = request.getParameter("town");
        if(town!=null && !"".equals(town)){
            address.setTown(town);
        }

        String addr = request.getParameter("shipAddr");
        address.setAddr(addr);

        String zip = request.getParameter("shipZip");
        address.setZip(zip);

        return address;
    }

    @ResponseBody
    @RequestMapping("/test1")
    public Map<String, String> to(int orderid) {
       Order  order=orderManager.get(orderid);
        Map<String, String> data = new HashMap<String, String>();

        // 将json字符串转换成jsonObject
        JSONObject jsonObject = JSONObject.fromObject(order.getItems_json());
        Iterator ite = jsonObject.keys();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            String value = jsonObject.get(key).toString();
            data.put(key, value);
        }
        // 或者直接将 jsonObject赋值给Map
        data = jsonObject;
        int pid=Integer.parseInt(data.get("product_id"));
        return data;
    }

    /**
     * //删除订单
     * @param orderid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteorder")
    public  JsonResult deleteOrder(Integer[] orderid,Integer userid){
        List<Order> order=orderManager.getByUserIdAndStatus(userid,null);
        if (order.size()==0){
            return  JsonResultUtil.getErrorJson("您还没有订单");
        }else {
            boolean  deleteorder= orderManager.delete(orderid);
            if (deleteorder){
                return JsonResultUtil.getSuccessJson("删除订单成功");
            }else {
                return JsonResultUtil.getSuccessJson("删除订单失败");
            }
        }
    }

    /**
     * //取消订单
     * @param orderid
     * @param reason
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/cancelorder")
    public  JsonResult cancelOrder(Integer orderid,String reason,Integer userid){
        try {
            orderManager.cancel(orderid,reason,userid);
        }catch (Exception e){
            return JsonResultUtil.getErrorJson("取消订单失败");
        }
       return JsonResultUtil.getSuccessJson("取消订单成功");
    }

    /**
     * //得到订单列表
     * @param userid
     * @param status
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOrderList")
    public  JsonResult getOrderList(Integer userid,Integer status){
      List<Order> orders=orderManager.getByUserIdAndStatus(userid,status);
      List list=new ArrayList();
      for (Order order:orders){
          Map map=new HashMap();
          map.put("paymentid",order.getPayment_id());
          map.put("orderid",order.getOrder_id());
          map.put("sn",order.getSn());
          map.put("status",order.getStatus());
          map.put("totalprice",order.getNeed_pay_money());
          int orderid=order.getOrder_id();
          //遍历订单项，判断商品是否更新，如果商品更新则显示快照按钮
          List<OrderItem> itemList;
          if(order.getItems_json().length()==2){
              List<Order> childOrders = orderManager.getChildOrders(orderid);
              itemList = new ArrayList<OrderItem>();
              if(childOrders!=null&&childOrders.size()>0){
                  for(Order corder : childOrders){
                      List<OrderItem> temlist = orderManager.listGoodsItems(corder.getOrder_id());
                      itemList.addAll(temlist);
                  }
              }
          }else{
              itemList =orderManager.listGoodsItems(orderid);
          }
          List list1=new ArrayList();
          for (OrderItem orderItem:itemList){
              int a=itemList.size();
              map.put("ordercount",a);
              Map map1=new HashMap();
//              map1.put("shopimg","http://djt-test.oss-cn-hangzhou.aliyuncs.com/IMAGE2017/11/23/b53af95a-915a-4eed-bdfb-9c273bba5c6d.png");
//              map1.put("shop","牧中商城");
              map1.put("goodsid",orderItem.getGoods_id());
              map1.put("goodsname",orderItem.getName());
              map1.put("goodsprice",orderItem.getPrice());
              map1.put("goodsnum",orderItem.getNum());
              map1.put("img", StaticResourcesUtil.transformPathapp(orderItem.getImage()));
              map1.put("policysn",orderItem.getUnit());
              int typeid=Integer.parseInt(goodsManager.get(orderItem.getGoods_id()).get("type_id").toString());
              if (typeid==69){
                  map1.put("productTypes",0);
              }else if (typeid==65){
                  map1.put("productTypes",1);
              }else {
                  map1.put("productTypes",2);
              }
              list1.add(map1);
          }
          map.put("goods",list1);
          list.add(map);
      }
      return JsonResultUtil.getObjectMessageJson(list,"得到订单列表");
    }

    public  JsonResult confirmDisaply(Integer userid){
        List<Order> orders=orderManager.getByUserIdAndStatus(userid,30);
        return  null;
    }


    /**
     * //订单详情
     * @param orderid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOrderById")
    public JsonResult getOrderByOrderId(Integer orderid,Integer userid){
       List<Order> orders =orderManager.getByUserIdAndStatus(userid,null);
       if (orders.size()==0){
           return JsonResultUtil.getErrorJson("您还没有订单");
       }
        Order order=orderManager.get(orderid);
        Map map=new HashMap();
        map.put("orderid",order.getOrder_id());
        map.put("ordersn",order.getSn());
        Integer addrid=order.getAddress_id();
        map.put("genter",memberAddressManager.getAddress(addrid).getGenter());
        map.put("orderstatus",order.getStatus());
        map.put("shipaddr",order.getShip_addr());
        map.put("shipname",order.getShip_name());
        map.put("shipmobile",order.getShip_mobile());
        map.put("ordertime",order.getOrdertime());
        map.put("payname",order.getPayment_name());
        map.put("orderprice",order.getNeed_pay_money());
        map.put("ordercount",order.getGoods_num());
        if (order.getReceipt()==1){//1有发票  2没发票
            map.put("receiptcontent",order.getReceipt_content());
            map.put("receipttitle",order.getReceipt_title());
            map.put("receipt",order.getReceipt_type());
            map.put("receiptname",order.getReceipt_name());
        }else {
            map.put("receiptcontent",order.getReceipt_content());
            map.put("receipttitle",order.getReceipt_title());
            map.put("receipt",order.getReceipt_type());
            map.put("receiptname",order.getReceipt_name());
        }
        List<OrderItem> list=orderManager.listGoodsItems(orderid);
        List list1=new ArrayList();
        for (OrderItem orderItem:list){
            Map map1=new HashMap();
            map1.put("goodsid",orderItem.getGoods_id());
            map1.put("goodimg",StaticResourcesUtil.transformPathapp(orderItem.getImage()));
            map1.put("goodname",orderItem.getName());
            list1.add(map1);
        }
        Map map2=new HashMap();
        map2.put("order",map);
        map2.put("goods",list1);
        return  JsonResultUtil.getObjectMessageJson(map2,"通过订单id得到订单详情");
    }



    /**
     * 创建订单号（日期+两位随机数）
     */
    private String createSn(){
        boolean isHave = true;  //数据库中是否存在该订单
        String sn = "";			//订单号

        //如果存在当前订单
        while(isHave) {
            StringBuffer  snSb = new StringBuffer(DateUtil.getDateline()+"") ;
            snSb.append(new Random().nextInt(100-10)+10);
            String sql = "SELECT count(order_id) FROM es_order WHERE sn = '" + snSb.toString() + "'";
            int count = this.daoSupport.queryForInt(sql);
            if(count == 0) {
                sn = snSb.toString();
                isHave = false;
            }
        }
        return sn;
    }

    /**
     * //用户确认收货
     * @param orderid
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/confirmOrder")
    public JsonResult confirmOrder(Integer orderid,Integer userid){
        List<Order> orders=orderManager.getByUserIdAndStatus(userid,null);
        if (orders==null){
            return JsonResultUtil.getErrorJson("您还没有订单信息");
        }
        Order order=orderManager.get(orderid);
        order.setStatus(OrderStatus.ORDER_COMPLETE);
        orderManager.edit(order);
        //销量+1
        List<OrderItem> orderItemList=orderManager.listGoodsItems(orderid);
        for (OrderItem orderItem:orderItemList){
            Integer goodsid=orderItem.getGoods_id();
            Goods goods=goodsManager.getGoods(goodsid);
            Integer buycount=goods.getBuy_count()+1;
            goods.setBuy_count(buycount);
            goodsManager.editapp(goods);
        }
        return JsonResultUtil.getSuccessJson("确认收货成功");
    }

    /**
     * //退货退款申请
     * @param userid
     * @param reason
     * @param orderid
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/sellbackapply")
    @Transactional
    public JsonResult sellbackapply(Integer userid,String reason,Integer orderid,HttpServletRequest request){
        try {
            //记录会员信息
            Member member =memberManager.get(userid);
            SellBack sellBack=new SellBack();
            sellBack.setReason(reason);
            sellBack.setMember_id(member.getMember_id());
            sellBack.setSndto(member.getName());//退货人
            sellBack.setTradeno(com.enation.framework.util.DateUtil.toString(DateUtil.getDateline(),"yyMMddhhmmss"));//退货单号
            sellBack.setRegoperator("会员["+member.getUname()+"]");//操作员
            sellBack.setTradestatus(0);//状态 0待审核。1.审核成功代发货. 4:已经入库  6:退款成功
            sellBack.setRegtime(DateUtil.getDateline());
            sellBack.setType(2);//1.退款 。2.退货
            sellBack.setOrderid(orderid);
            sellBack.setRefund_way("信用额度");
            sellBack.setReturn_account(memberManager.get(userid).getUname());
            sellBack.setApply_alltotal(orderManager.get(orderid).getPaymoney());
            int sellbackid= sellBackManager.addSellBackapp1(sellBack);
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            for (MultipartFile multipartFile:files){
                String fileName=multipartFile.getOriginalFilename();
                if(!FileUtil.isAllowUpImg(fileName)){
                    throw new IllegalArgumentException("不被允许的上传文件类型");
                }
                String ext = FileUtil.getFileExt(fileName);
                fileName = DateUtil.toString(new Date(), "mmss") + StringUtil.getRandStr(4) + "." + ext;
                String static_server_path= SystemSetting.getStatic_server_path();
                String filePath =  static_server_path + "/attachment/";
                String subFolder="sellback";
                if(subFolder!=null){
                    filePath+=subFolder +"/";
                }
                String timePath=this.getTimePath();
                String path  = EopSetting.FILE_STORE_PREFIX+ "/attachment/" +(subFolder==null?"":subFolder)+"/"+timePath+"/"+fileName;
                filePath +=timePath;
                filePath += fileName;
                try {
                    FileUtil.write(multipartFile.getInputStream(),filePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String sellbackgalleryimg=path;
                int i=1;
                Sellbackgallery sellbackgallery=new Sellbackgallery();
                sellbackgallery.setCreatetime(new Timestamp(System.currentTimeMillis()));
                sellbackgallery.setOriginal(sellbackgalleryimg);
                sellbackgallery.setSellbackid(sellbackid);
                orderManager.createSellBackGralley(sellbackgallery);
            }
            /**
             * 循环页面中选中的商品，形成退货明细:goodsList
             */
            List goodsList = new ArrayList();
            Order order=orderManager.get(orderid);
            int goodnum=order.getGoods_num();
            List<OrderItem> orderItems=orderManager.listGoodsItems(orderid);
            for(int i=0;i<goodnum;i++){
                for (OrderItem orderItem1:orderItems){
                    SellBackGoodsList sellBackGoods = new SellBackGoodsList();
                    sellBackGoods.setPrice(orderItem1.getPrice());
                    sellBackGoods.setReturn_num(orderItem1.getNum());
                    sellBackGoods.setShip_num(orderItem1.getShip_num());
                    sellBackGoods.setGoods_id(orderItem1.getGoods_id());
                    sellBackGoods.setGoods_remark(reason);
                    sellBackGoods.setProduct_id(orderItem1.getProduct_id());
                    sellBackGoods.setItem_id(orderItem1.getItem_id());
                    goodsList.add(sellBackGoods);
                }
            }
            //记录会员信息   退款
            Member member1 =memberManager.get(userid);
            SellBack sellBack1=new SellBack();
            sellBack1.setReason(reason);
            sellBack1.setMember_id(member1.getMember_id());
            sellBack1.setSndto(member1.getName());
            sellBack1.setTradeno(com.enation.framework.util.DateUtil.toString(DateUtil.getDateline(),"yyMMddhhmmss"));//退款单号
            sellBack1.setRegoperator("会员["+member1.getUname()+"]");
            sellBack1.setTradestatus(0);
            sellBack1.setRegtime(DateUtil.getDateline());
            sellBack1.setType(1);
            sellBack1.setOrderid(orderid);
            sellBack1.setRefund_way("信用额度");
            sellBack1.setReturn_account(memberManager.get(userid).getUname());
            sellBack1.setApply_alltotal(orderManager.get(orderid).getPaymoney());
            sellBackManager.addSellBackapp(sellBack1);
            //return JsonResultUtil.getSuccessJson("退款申请成功");
            //this.sellBackManager.addSellBack(sellBack, goodsList);
            return JsonResultUtil.getSuccessJson("退货退款申请成功");
        } catch (RuntimeException e) {
            return JsonResultUtil.getErrorJson("退货退款申请失败：" + e.getMessage());
        }
    }

    /**
     * //退货list
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getSellBackList")
    public JsonResult getSellBackList(Integer userid){
        List<SellBack> sellBacks=sellBackManager.list(userid);
        if (sellBacks==null){
            return JsonResultUtil.getErrorJson("查看退货list出错");
        }
        Map map1=new HashMap();
        List list1=new ArrayList();
        for (SellBack sellBack:sellBacks){
            List list=new ArrayList();
            int sellbackid=sellBack.getId();
             List<SellBackGoodsList> sellBackGoodsLists=sellBackManager.getGoodsListByRecid(sellbackid);
             for (SellBackGoodsList sellBackGoodsList:sellBackGoodsLists){
                 Map map=new HashMap();
                 map.put("sellbackstatus",sellBack.getTradestatus());//状态 0待审核。1.审核成功代发货. 4:已经入库  6:退款成功
                 map.put("sellbackid",sellBackGoodsList.getRecid());
                 int sellbacid=sellBackGoodsList.getRecid();
                 try {
                     Long refundtime=sellBackManager.getRefund(sellbacid).getRefund_time();
                     map.put("sellbacktime",refundtime);
                 }catch (Exception e){
                     map.put("sellbacktime",null);
                 }
                 map.put("sellbackgoodsname",sellBackGoodsList.getGoods_name());
                 map.put("sellbackgoodsprice",sellBackGoodsList.getPrice());
                 map.put("sellbackgoodsnum", sellBackGoodsList.getReturn_num());
                 map.put("sellbackgoodsimg",StaticResourcesUtil.transformPathapp(sellBackGoodsList.getGoods_image()));
                 list.add(map);
             }
            list1.add(list);
        }
        map1.put("list",list1);
        return  JsonResultUtil.getObjectMessageJson(map1,"退货list");
    }

    /**
     * //退货list
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getSellBackList1")
    public JsonResult getSellBackList1(Integer userid){
        List<SellBack> sellBacks=sellBackManager.list(userid);
        if (sellBacks==null){
            return JsonResultUtil.getErrorJson("查看退货list出错");
        }
        List list2=new ArrayList();
        for (SellBack sellBack:sellBacks){
            Map map1=new HashMap();
            Map map2=new HashMap();
            int sellbackid=sellBack.getId();
            map2.put("sellbackstatus",sellBack.getTradestatus());//状态 0待审核。1.审核成功代发货. 4:已经入库  6:退款成功
            map2.put("sellbackid",sellbackid);
            List list=new ArrayList();
            List<SellBackGoodsList> sellBackGoodsLists=sellBackManager.getGoodsListByRecid(sellbackid);
            for (SellBackGoodsList sellBackGoodsList:sellBackGoodsLists){
                Map map=new HashMap();
                int sellbacid=sellBackGoodsList.getRecid();
                try {
                    Long refundtime=sellBackManager.getRefund(sellbacid).getRefund_time();
                    map2.put("sellbacktime",refundtime*1000);
                }catch (Exception e){
                    map2.put("sellbacktime",0L);
                }
                map.put("sellbackgoodsname",sellBackGoodsList.getGoods_name());
                map.put("sellbackgoodsprice",sellBackGoodsList.getPrice());
                map.put("sellbackgoodsnum", sellBackGoodsList.getReturn_num());
                map.put("sellbackgoodsimg",StaticResourcesUtil.transformPathapp(sellBackGoodsList.getGoods_image()));
                list.add(map);
            }
            map1.put("sellbackdetail",list);
            map1.put("sellback",map2);
            list2.add(map1);
        }

        return  JsonResultUtil.getObjectMessageJson(list2,"退货list");
    }


    /**
     * //退货Detail
     * @param userid
     * @param sellbackid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getSellBackDetail")
    public JsonResult getSellBackDetail(Integer userid,Integer sellbackid){
        List<SellBack> sellBacks=sellBackManager.list(userid);
        if (sellBacks==null){
            return JsonResultUtil.getErrorJson("查看退货详情错误");
        }
        List<SellBackGoodsList> sellBackGoodsLists=sellBackManager.getGoodsListByRecid(sellbackid);
        List list=new ArrayList();
        Map map=new HashMap();
        List<Double> price=new ArrayList<Double>();
        for (SellBackGoodsList sellBackGoodsList:sellBackGoodsLists){
            Map map1=new HashMap();
            SellBack sellBack=sellBackManager.get(sellbackid);
            map.put("sellbackstatus",sellBack.getTradestatus());
            map.put("sellbacksn",sellBack.getTradeno());
            map1.put("sellbackgoodsname",sellBackGoodsList.getGoods_name());
            map1.put("sellbackgoodsimg",StaticResourcesUtil.transformPathapp(sellBackGoodsList.getGoods_image()));
            map1.put("sellbackgoodsnum",sellBackGoodsList.getReturn_num());
            map1.put("sellbackgoodsprice",sellBackGoodsList.getPrice());
            map.put("reason",sellBack.getReason());
            price.add(sellBackGoodsList.getReturn_num()*sellBackGoodsList.getPrice());
            try {
                Long refundtime=sellBackManager.getRefund(sellbackid).getRefund_time();
                map.put("sellbacktime",refundtime*1000);
            }catch (Exception e){
                map.put("sellbacktime",0L);
            }
            list.add(map1);
        }
        double pricetotal=0.0;
        for (Double d:price){
            pricetotal+=d;
        }
        map.put("pricetotal",pricetotal);
        List<Sellbackgallery> sellbackgalleries=sellBackManager.getSellBackGralleyqq(sellbackid);
        List list1=new ArrayList();
        if (sellbackgalleries==null){
            list1=null;
        }else {
            for (Sellbackgallery sellbackgallery:sellbackgalleries){
                Map map3=new HashMap();
                map3.put("sellbackimg",StaticResourcesUtil.transformPathapp(sellbackgallery.getOriginal()));
                list1.add(map3);
            }
        }
        map.put("img",list1);
        map.put("detail",list);
        return  JsonResultUtil.getObjectMessageJson(map,"退货Detail");
    }
    private String getTimePath(){
        Calendar now = Calendar.getInstance();
        int year=now.get(Calendar.YEAR);
        int month=now.get(Calendar.MONTH) + 1;
        int date=now.get(Calendar.DAY_OF_MONTH);
        int minute=now.get(Calendar.HOUR_OF_DAY);
        String filePath="";
        if(year!=0){
            filePath+=year+"/";;
        }
        if(month!=0){
            filePath+=month+"/";;
        }
        if(date!=0){
            filePath+=date+"/";;
        }
        if(minute!=0){
            filePath+=minute+"/";;
        }
        return  filePath;
    }

    private String createSession(){
        String sn = "";
        StringBuffer  snSb = new StringBuffer(DateUtil.getDateline()+"") ;
        snSb.append(new Random().nextInt(100-10)+10);
        sn = snSb.toString();
        return sn;
    }


    /**
     * //售后判断
     * @param userid
     * @param orderid
     * @return
     */
    @ResponseBody
    @RequestMapping("/coformSellBack")
    public JsonResult coformSellBack(Integer userid,Integer orderid){
        Order order1=orderManager.get(orderid);
//        if (userid!=order1.getMember_id()){
//            return JsonResultUtil.getErrorJson("您没有权限哦");
//        }
        Long deadline=order1.getOrdertime()+1000*60*60*24*15;
        if (deadline<new Date().getTime()){
            return JsonResultUtil.getErrorJson("已经超出了售后时间噢");
        }else {
            return JsonResultUtil.getSuccessJson("可以申请售后");
        }
    }
}
